package com.yuandian.business.monitor.service.impl;

import cn.hutool.core.stream.StreamUtil;
import com.yuandian.api.management.feign.RemoteExclusiveIndicatorService;
import com.yuandian.bpm.common.core.constant.SecurityConstants;
import com.yuandian.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * <p> 专属指标工具类 </p>
 *
 * @Author: LinShiHe
 * @Date: 2022/3/10 0:10
 */
@Slf4j
@Component
public class ExclusiveIndicator {

	@Autowired
	private RemoteExclusiveIndicatorService remoteExclusiveIndicatorService;
	private static RemoteExclusiveIndicatorService staticRemoteExclusiveIndicatorService;
	@PostConstruct
	public void init() {
		staticRemoteExclusiveIndicatorService = this.remoteExclusiveIndicatorService;
	}

	/**
     * 切割专属指标中指定的字段值
     * @param map
     * @param resType 经过集格式
     *                    1：表示需要构建复杂Map格式如：Map<String, Map<String, String>>
     *                    2：表示需要构建简单的Map格式如：Map<String, String>
     */
    public static void getValueFromSpecifyParameters(Map<String, Object> map, LinkedHashMap<String, Object> customMap) {
        String exclusiveIndicator = map.get("exclusiveIndicator") == null ? "" : map.get("exclusiveIndicator").toString();

        if (customMap == null) { customMap = new LinkedHashMap<>(); }
        Map<String, LinkedHashSet<String>> temporaryMap = new LinkedHashMap<>();

        String mesgArr[] = exclusiveIndicator.split("\\|");
        for (String keyValue : mesgArr) {
            String[] s = keyValue.split("=");
            if(customMap.get(s[0]) != null && !"".equals(customMap.get(s[0]))) {
                if(s.length == 2) {
                    temporaryMap.computeIfAbsent(s[0], k -> new LinkedHashSet<>());
                    temporaryMap.get(s[0]).add(s[1]);
                }
            }
        }

        // 构建简单 Map<String, String> 集合
        for (Map.Entry<String, Object> entry : customMap.entrySet()) {
            String key = entry.getKey();
            Set<String> set = temporaryMap.get(key);
            String valueStr = (set == null ? "" : StreamUtil.join(Arrays.stream(set.toArray()), ","));
            map.put(key, valueStr);
        }

    }

    /**
     * 切割专属指标中指定的字段值
     * @param customMap
     * @param exclusiveIndicator
     */
    public static LinkedHashMap<String, Object> getValueFromSpecifyParameters(LinkedHashMap<String, Object> customMap, String exclusiveIndicator) {

        if (customMap == null) { customMap = new LinkedHashMap<>(); }
        if (StringUtils.isEmpty(exclusiveIndicator)) { exclusiveIndicator = ""; }
        LinkedHashMap<String, Object> resMap = new LinkedHashMap<>();

        Map<String, LinkedHashSet<String>> temporaryMap = new LinkedHashMap<>();

        String mesgArr[] = exclusiveIndicator.split("\\|");
        for (String keyValue : mesgArr) {
            String[] s = keyValue.split("=");
            if(customMap.get(s[0]) != null && !"".equals(customMap.get(s[0]))) {
                if(s.length == 2) {
                    temporaryMap.computeIfAbsent(s[0], k -> new LinkedHashSet<>());
                    temporaryMap.get(s[0]).add(s[1]);
                }
            }
        }

        for (Map.Entry<String, Object> entry : customMap.entrySet()) {
            String key = entry.getKey();
            Set<String> set = temporaryMap.get(key);
            String valueStr = ((set == null || set.size() == 0 ) ? "" : StringUtils.join(",", set.toArray()));
            resMap.put(key, valueStr);
        }
        return resMap;
    }

	/**
	 * 处理专属指标：根据配置显示
	 */
	public static String getIndicatorWithSet(String exclusiveIndicator, List<String> list) {
		log.info("进入专属指标处理方法");
		if (StringUtils.isEmpty(exclusiveIndicator)) {
			log.info("待处理的专属指标为空字符串！");
			return exclusiveIndicator;
		}
		if (list == null || list.size() == 0) {
			log.info("暂无要显示的专属指标！");
			return "";
		}
		log.info("开始处理专属指标，专属指标字符串：{}，要显示的专属指标：{}", exclusiveIndicator, list.toString());
		String msgArr[] = exclusiveIndicator.split("\\|");
		StringBuilder builder = new StringBuilder();
		for (String indicator : msgArr) {
			if(!indicator.contains("=")){
				continue;
			}
			String key = indicator.substring(0, indicator.indexOf("="));//专属指标
			if (!list.contains(key)) {
				log.info("专属指标名：{}不显示", key);
				continue;
			}
			String value = indicator.substring(indicator.indexOf("="));//专属指标值
			builder.append(key).append(value).append("|");
		}
		String resultStr = builder.toString();
		if (StringUtils.isNotEmpty(resultStr)) {
			resultStr = resultStr.substring(0, resultStr.length() - 1);
		}
		log.info("处理后的专属指标：{}", resultStr);
		return resultStr;
	}

    /**
     * 获取自定义字段
     * @return
     */
    public LinkedHashMap<String, Object> getCustomMap() {
        Map<String, Object> customMap = new LinkedHashMap<>();
		Map<String, Object> map = null ;
		try {
			map = remoteExclusiveIndicatorService.assemblyDisplayField(new HashMap<>());
		}catch (Exception e){
			log.error("调用远程接口获取自定义专属指标异常，异常原因：{}",e.getMessage());
		}
        if (map != null) {
            customMap = (LinkedHashMap<String, Object>) map.get("exclusiveIndicator");
        }
        return (LinkedHashMap<String, Object>) customMap;
    }
	public LinkedHashMap<String, Object> getCustomMapInner() {
        Map<String, Object> customMap = new LinkedHashMap<>();
		Map<String, Object> map = null ;
		try {
			map = remoteExclusiveIndicatorService.assemblyDisplayField(new HashMap<>(), SecurityConstants.FROM_IN);
		}catch (Exception e){
			log.error("调用远程接口获取自定义专属指标异常，异常原因：{}",e.getMessage());
		}
        if (map != null) {
            customMap = (LinkedHashMap<String, Object>) map.get("exclusiveIndicator");
        }
        return (LinkedHashMap<String, Object>) customMap;
    }
}
